﻿
Imports ajayumi.develop.win32.GRssReader.Google.Reader
Imports System.ComponentModel
Imports System.IO
Imports System.Xml
Imports System.Text
Imports ajayumi.develop.win32.GRssReader.Service.Model
Imports System.ServiceModel.Syndication


Public Class FrmMain

#Region "Variables"

#End Region

#Region "Methods"

    ''' <summary>
    ''' 添加节点
    ''' </summary>
    ''' <param name="control"></param>
    ''' <param name="node"></param>
    ''' <remarks></remarks>
    Private Sub addNode(control As TreeView, node As TreeNode)
        If control.InvokeRequired Then
            control.Invoke(New Action(Of TreeView, TreeNode)(AddressOf Me.addNode), New Object() {control, node})
        Else
            control.Nodes.Add(node)
        End If
    End Sub

    Private Sub addGroup(control As ListView, group As ListViewGroup)
        If control.InvokeRequired Then
            control.Invoke(New Action(Of ListView, ListViewGroup)(AddressOf Me.addGroup), New Object() {control, group})
        Else
            control.Groups.Add(group)
        End If
    End Sub

    Private Sub addItem(control As ListView, item As ListViewItem)
        If control.InvokeRequired Then
            control.Invoke(New Action(Of ListView, ListViewItem)(AddressOf Me.addItem), New Object() {control, item})
        Else
            control.Items.Add(item)
        End If
    End Sub

    Private Sub setNodeText(control As TreeView, node As TreeNode, text As String)
        If control.InvokeRequired Then
            control.Invoke(New Action(Of TreeView, TreeNode, String)(AddressOf Me.setNodeText), New Object() {control, node, text})
        Else
            node.Text = text
        End If
    End Sub


    Private Sub FillArticle(articleInfos As IEnumerable(Of ArticleInfo))
        Me.lvArticles.Invoke(New Action(AddressOf Me.lvArticles.Groups.Clear))
        Me.lvArticles.Invoke(New Action(AddressOf Me.lvArticles.Items.Clear))

        Dim _ArticleInfoGroups = From o As ArticleInfo In articleInfos _
                                 Group By o.LastUpdatedTime.Date Into Group, Count()

        For Each _ArticleInfoGroup In _ArticleInfoGroups
            Dim _ListViewGroup As New ListViewGroup(_ArticleInfoGroup.Date.ToString("yyyy-MM-dd"))
            For Each _ArticleInfo In _ArticleInfoGroup.Group
                Dim _ListViewItem As New ListViewItem(_ListViewGroup) With _
                    {.Tag = _ArticleInfo, .Text = _ArticleInfo.TitleText}
                Me.addItem(Me.lvArticles, _ListViewItem)
            Next
            Me.addGroup(Me.lvArticles, _ListViewGroup)
        Next
    End Sub

#End Region

#Region "获取订阅列表"

    Private Sub bgwSubscription_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgwSubscription.DoWork
        Dim bgw As BackgroundWorker = DirectCast(sender, BackgroundWorker)
        Try
            Me.tvSubscriptions.Invoke(New Action(AddressOf Me.tvSubscriptions.Nodes.Clear))
            Dim _SubscriptionInfoList As List(Of SubscriptionInfo) = o_ReaderService.GetSubscriptionInfoList()
            Dim _SubscriptionInfoGroups = From o As SubscriptionInfo In _SubscriptionInfoList _
                                          Group By o.Category Into Group, Sum(o.UnReadCount)

            For Each _SubscriptionInfoGroup In _SubscriptionInfoGroups
                Dim _ParentNode As New TreeNode()
                Dim _GroupCount As Integer = _SubscriptionInfoGroup.Group.Count

                For Each _SubscriptionInfo As SubscriptionInfo In _SubscriptionInfoGroup.Group
                    Dim _ChildNode As TreeNode = Nothing

                    If _SubscriptionInfo.UnReadCount > 0 Then
                        _ChildNode = New TreeNode(String.Format("{0} (未读文章：{1})", _SubscriptionInfo.TitleText, _SubscriptionInfo.UnReadCount))
                        _ChildNode.ForeColor = Color.Blue
                    Else
                        _ChildNode = New TreeNode(_SubscriptionInfo.TitleText)
                    End If

                    Dim _FeedService As FeedServiceBase = Nothing
                    Select Case o_ReaderMode
                        Case ReaderMode.Offline
                            _FeedService = New OfflineFeedService(_ChildNode, _SubscriptionInfo)
                        Case Else
                            _FeedService = New OnlineFeedService(_ChildNode, _SubscriptionInfo)
                    End Select
                    With _FeedService
                        AddHandler .GetArticleImageProgressChanged, AddressOf Me.Feed_GetArticleImageProgressChanged
                        AddHandler .GetArticleCompleted, AddressOf Me.Feed_GetArticleCompleted
                    End With

                    _ChildNode.Tag = _FeedService
                    _ParentNode.Nodes.Add(_ChildNode)
                Next

                _ParentNode.Text = String.Format("{0} (未读文章：{1}，订阅：{2})", _
                                                 IIf(String.IsNullOrEmpty(_SubscriptionInfoGroup.Category), "未分类", _SubscriptionInfoGroup.Category), _
                                                 _SubscriptionInfoGroup.Sum, _
                                                 _GroupCount)
                Me.addNode(Me.tvSubscriptions, _ParentNode)
            Next

        Catch ex As Exception
            MsgBox(ex.Message)
            bgw.CancelAsync()
        End Try
    End Sub

    Private Sub bgwSubscription_RunWorkerCompleted(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgwSubscription.RunWorkerCompleted
        Me.tsslbMsg.Text = "获取订阅列表完成"
        Me.tsbtnSyncArticles.Enabled = (o_ReaderMode = ReaderMode.Online)
    End Sub

#End Region

#Region "Feed Service"

    Private Sub Feed_GetArticleImageProgressChanged(sender As Object, e As GetArticleImageProgressChangedEventArgs)
        Dim _FeedService As FeedServiceBase = DirectCast(e.Node.Tag, FeedServiceBase)
        Dim _NodeText As String = String.Empty
        If _FeedService.SubscriptionInfo.UnReadCount > 0 Then
            _NodeText = String.Format("{0} (未读文章：{1}，资源下载：{2}%)", _
                                      _FeedService.SubscriptionInfo.TitleText, _
                                      _FeedService.SubscriptionInfo.UnReadCount, _
                                      e.ProgressPercentage)
        Else
            _NodeText = String.Format("{0} (资源下载：{1}%)", _
                                      _FeedService.SubscriptionInfo.TitleText, _
                                      e.ProgressPercentage)
        End If
        Me.setNodeText(Me.tvSubscriptions, e.Node, _NodeText)
    End Sub

    Private Sub Feed_GetArticleCompleted(sender As Object, e As GetArticleInfoListCompleted)
        Me.FillArticle(e.ArticleInfoList)

        Dim _FeedService As FeedServiceBase = DirectCast(e.UserState, FeedServiceBase)
        Me.tsslbMsg.Text = String.Format("{0} 下的文章获取完成，下载图片资源任务将在后台运行...", _FeedService.SubscriptionInfo.TitleText)
    End Sub

#End Region

    Private Sub tvSubscriptions_NodeMouseClick(sender As System.Object, e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles tvSubscriptions.NodeMouseClick
        Dim _FeedService As FeedServiceBase = DirectCast(e.Node.Tag, FeedServiceBase)
        If _FeedService Is Nothing Then Exit Sub

        Me.TabControl1.SelectTab(Me.tabArticleList)
        Me.tabArticleList.Text = _FeedService.SubscriptionInfo.TitleText

        _FeedService.GetArticleInfos(My.Settings.MaxArticleCount)
    End Sub


    Private Sub FrmMain_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        Try
            For Each _TreeNode As TreeNode In Me.tvSubscriptions.Nodes
                For Each _ChilderNode As TreeNode In _TreeNode.Nodes
                    If _ChilderNode.Tag IsNot Nothing Then
                        Dim _FeedService As FeedServiceBase = DirectCast(_ChilderNode.Tag, FeedServiceBase)
                        _FeedService.Dispose()
                    End If
                Next
            Next

            If o_ReaderService IsNot Nothing Then
                o_ReaderService.Update()
                o_ReaderService.Dispose()
            End If

            '删除下载缓存文件夹
            Directory.Delete(GetDownloadCacheFolder(), True)
        Catch ex As Exception

        End Try
    End Sub

    Private Sub tsbtnSetting_Click(sender As System.Object, e As System.EventArgs) Handles tsbtnSetting.Click
        Dim _FrmSetting As New FrmSetting()
        _FrmSetting.Show()
    End Sub

    Private Sub tsbtnLogout_Click(sender As System.Object, e As System.EventArgs) Handles tsbtnLogout.Click
        My.Settings.UserName = String.Empty
        My.Settings.Password = String.Empty
        My.Settings.Save()

        Application.Restart()
    End Sub


#Region "获取订阅条目内容"

    Private Sub bgwFeed_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgwFeed.DoWork
        Dim _bgw As BackgroundWorker = DirectCast(sender, BackgroundWorker)
        Dim _TreeNodes() As TreeNode = DirectCast(e.Argument, TreeNode())
        Dim _Index As Integer = 1
        Dim _Total As Integer = _TreeNodes.Length
        For Each _TreeNode As TreeNode In _TreeNodes
            Dim _FeedService As FeedServiceBase = DirectCast(_TreeNode.Tag, FeedServiceBase)
            Try
                _FeedService.GetArticleInfos()

                Dim _PercentProgress As Integer = CInt((_Index / _Total) * 100.0!)
                _bgw.ReportProgress(_PercentProgress)

                _Index += 1
            Catch ex As Exception
                Dim _NodeText As String = String.Empty
                If _FeedService.SubscriptionInfo.UnReadCount > 0 Then
                    _NodeText = String.Format("{0} (未读文章：{1}) {2}", _
                                                   _FeedService.SubscriptionInfo.TitleText, _
                                                   _FeedService.SubscriptionInfo.UnReadCount, _
                                                   ex.Message)
                Else
                    _NodeText = String.Format("{0} {1}", _FeedService.SubscriptionInfo.TitleText, ex.Message)

                End If
                Me.setNodeText(Me.tvSubscriptions, _TreeNode, _NodeText)
            End Try
        Next

    End Sub

    Private Sub bgwFeed_ProgressChanged(sender As System.Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgwFeed.ProgressChanged
        Me.tsslbMsg.Text = String.Format("获取订阅条目中 ({0}%)", e.ProgressPercentage)
    End Sub

    Private Sub bgwFeed_RunWorkerCompleted(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgwFeed.RunWorkerCompleted
        Me.tsslbMsg.Text = "获取订阅条目文章完成，下载图片资源任务将在后台运行..."
        Me.tsbtnSyncArticles.Enabled = True
    End Sub

#End Region

    Private Sub FrmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Me.tsslbMsg.Text = "开始获取订阅列表..."
        Me.tsbtnSyncArticles.Enabled = False
        Me.bgwSubscription.RunWorkerAsync()
    End Sub

    Private Sub tsbtnSyncArticles_Click(sender As System.Object, e As System.EventArgs) Handles tsbtnSyncArticles.Click
        Dim _TreeNodeList As New List(Of TreeNode)()
        For Each _TreeNode As TreeNode In Me.tvSubscriptions.Nodes
            For Each _ChilderNode As TreeNode In _TreeNode.Nodes
                If _ChilderNode.Tag IsNot Nothing Then
                    _TreeNodeList.Add(_ChilderNode)
                End If
            Next
        Next

        Me.tsslbMsg.Text = "开始获取所有订阅条目文章..."
        Me.tsbtnSyncArticles.Enabled = False
        Me.bgwFeed.RunWorkerAsync(_TreeNodeList.ToArray())

    End Sub

    Private Sub lvArticles_ItemSelectionChanged(sender As System.Object, e As System.Windows.Forms.ListViewItemSelectionChangedEventArgs) Handles lvArticles.ItemSelectionChanged
        Dim _ArticleInfo As ArticleInfo = DirectCast(e.Item.Tag, ArticleInfo)
        Me.WebBrowser1.DocumentText = _ArticleInfo.SummayText
        Try
            o_ReaderService.AddState(_ArticleInfo, State.Read)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub tsbtnClearSelected_Click(sender As System.Object, e As System.EventArgs) Handles tsbtnClearSelected.Click
        Dim _TreeNode As TreeNode = Me.tvSubscriptions.SelectedNode
        If _TreeNode Is Nothing Then Exit Sub

        Dim _FeedService As FeedServiceBase = DirectCast(_TreeNode.Tag, FeedServiceBase)
        _FeedService.Clear()
        Me.tsslbMsg.Text = String.Format("{0} 缓存清除完毕", _FeedService.SubscriptionInfo.TitleText)
    End Sub

    Private Sub ToolStripButton1_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton1.Click
        Console.WriteLine(Me.tvSubscriptions.Nodes(0).NextVisibleNode)
    End Sub
End Class
